import useAuthStore from '@/stores/auth'

class BaseUserHttp {
    constructor() {
        this.baseUrl = import.meta.env.VITE_BASE_USER_URL
    }
    _build_full_url(url) {
        return this.baseUrl + url;
    }
    
    async _request(path,params,method='GET', retryCount = 0){
        const url=this._build_full_url(path);
        const authStore = useAuthStore()
        const response=await uni.request({
            url:url,
            method:method,
            data:params,
            header:{
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + authStore.access_token
            }
        })
        if (response.statusCode === 200) {
            return response.data
        }else if (response.statusCode === 403 && retryCount < 3) {
            await this.update_access_token()
            return this._request(path, params, method, retryCount + 1)
        }else if (response.statusCode === 403 && retryCount >= 3) {
            uni.showToast({
                title: 'token刷新失败，请重新登录',
                icon: 'none'
            })
            authStore.clearUserToken()
            uni.switchTab({
                url: '/pages/index/index'
            })
            throw new Error('token刷新失败，请重新登录')
        }else{
            uni.showToast({
                title: response.data.detail,
                icon: 'none'
            })
        }
        
    }
    update_access_token=async ()=>{
        const url=this._build_full_url('/user/refresh/token')
        const authStore=useAuthStore()
        if (!authStore.is_logined) {
            uni.showToast({
                title: '请先登录',
                icon: 'none'
            })
            throw new Error('用户未登录')
        }
        const response=await uni.request({
            url: url,
            method: 'GET',
            header: {
                Authorization: 'Bearer ' + authStore.refresh_token
            },
        })
        if (response.statusCode == 200) {
            let access_token = response.data.access_token;
            console.log("current access_token:",access_token)
			authStore.setAccessToken(access_token);
            
        } else if(response.statusCode == 401) {
            uni.switchTab({
                url: '/pages/index/index'
            })
            throw new Error('登录过期，请重新登录')
        }
    }
    get(path,params){
        return this._request(path,params,'GET');
    }
    post(path,params){
        return this._request(path,params,'POST');
    }
    put(path,params){
        return this._request(path,params,'PUT');
    }
    delete(path,params){
        return this._request(path,params,'DELETE');
    }
    uploadFile(path,params){
        return this._request(path,params,'POST');
    }
    downloadFile(path,params){
        return this._request(path,params,'GET');
    }
}
export default new BaseUserHttp();
